import sys
import os
import datetime
import re

import settings
import logging


log = logging.getLogger(settings.log_name_applog)


def get_date():
    return datetime.datetime.now().strftime('%m-%d-%y')


#verified at #14
def get_latest_app_log_filepath():
    filelist = filter(os.path.isfile, [settings.app_log_path +
                                       name for name in os.listdir(settings.app_log_path)])

    if bool(filelist):
        filepath = max(filelist, key=os.path.getmtime)
        return os.path.abspath(filepath)

    else:
        return 'EMPTY'


#verified at #14
def get_latest_link_log_filepath():
    filelist = filter(os.path.isfile, [settings.links_log_path +
                                       name for name in os.listdir(settings.links_log_path)])

    if bool(filelist):
        filepath = max(filelist, key=os.path.getmtime)
        return os.path.abspath(filepath)

    else:
        return 'EMPTY'


#verified at #14
def get_latest_downloader_log_filepath():
    filelist = filter(os.path.isfile, [settings.downloader_log_path +
                                       name for name in os.listdir(settings.downloader_log_path)])

    if bool(filelist):
        filepath = max(filelist, key=os.path.getmtime)
        return os.path.abspath(filepath)

    else:
        return 'EMPTY'


def get_latest_downloader_completed_log_filepath():
    filelist = filter(os.path.isfile, [settings.downloader_logging_file_completed_path +
                                       name for name in os.listdir(settings.downloader_logging_file_completed_path)])

    if bool(filelist):
        filepath = max(filelist, key=os.path.getmtime)
        return os.path.abspath(filepath)

    else:
        return 'EMPTY'


def get_latest_downloader_failed_log_filepath():
    filelist = filter(os.path.isfile, [settings.downloader_logging_file_failed_path +
                                       name for name in os.listdir(settings.downloader_logging_file_failed_path)])

    if bool(filelist):
        filepath = max(filelist, key=os.path.getmtime)
        return os.path.abspath(filepath)

    else:
        return 'EMPTY'


def get_latest_downloader_todo_log_filepath():
    filelist = filter(os.path.isfile, [settings.downloader_logging_file_todo_path +
                                       name for name in os.listdir(settings.downloader_logging_file_todo_path)])

    if bool(filelist):
        filepath = max(filelist, key=os.path.getmtime)
        return os.path.abspath(filepath)

    else:
        return 'EMPTY'


#verified at #14
def init_latest_downloader_log_filepath():
    filepath_pattern = get_date() + '_id_[0-9].+\.txt'
    filepath = get_latest_downloader_log_filepath()

    if not re.search(filepath_pattern, filepath) is None:
        try:
            index = filepath.split(settings.log_file_delimiter)[settings.downloader_log_id_index]

        except IndexError:
            log.warning('downloader log file ' + filepath + ' has invalid naming format.')
            index = '-1'

        index = str((int(index)) + 1)

    else:
        index = '0'

    return __create_new_downloader_log_file(index)


def init_latest_downloader_completed_log_filepath():
    filepath_pattern = get_date() + '_id_[0-9].+\.txt'
    filepath = get_latest_downloader_completed_log_filepath()

    if not re.search(filepath_pattern, filepath) is None:
        try:
            index = filepath.split(settings.log_file_delimiter)[settings.downloader_log_id_index]

        except IndexError:
            log.warning('downloader log file ' + filepath + ' has invalid naming format.')
            index = '-1'

        index = str((int(index)) + 1)

    else:
        index = '0'

    return __create_new_downloader_completed_log_file(index)


def init_latest_downloader_failed_log_filepath():
    filepath_pattern = get_date() + '_id_[0-9].+\.txt'
    filepath = get_latest_downloader_failed_log_filepath()

    if not re.search(filepath_pattern, filepath) is None:
        try:
            index = filepath.split(settings.log_file_delimiter)[settings.downloader_log_id_index]

        except IndexError:
            log.warning('downloader log file ' + filepath + ' has invalid naming format.')
            index = '-1'

        index = str((int(index)) + 1)

    else:
        index = '0'

    return __create_new_downloader_failed_log_file(index)


#verified at #14
def init_latest_link_log_filepath():
    filepath_pattern = get_date() + '_id_[0-9].+\.txt'
    filepath = get_latest_link_log_filepath()

    if not re.search(filepath_pattern, filepath) is None:
        try:
            index = filepath.split(settings.log_file_delimiter)[settings.downloader_log_id_index]

        except IndexError:
            log.warning('downloader log file ' + filepath + ' has invalid naming format.')
            index = '-1'

        index = str((int(index)) + 1)

    else:
        index = '0'

    return __create_new_link_log_file(index)


#verified at #14
def __create_new_link_log_file(file_index):
    filepath = settings.links_log_path + get_date() +\
               settings.log_file_delimiter + 'id' + settings.log_file_delimiter +\
               file_index + settings.log_file_delimiter + '.txt'

    open(filepath, 'w').close()
    log.info('created log file ' + filepath)
    return filepath


#verified at #14
def __create_new_downloader_log_file(file_index):
    filepath = settings.downloader_logging_file_path + get_date() +\
               settings.log_file_delimiter + 'id' + settings.log_file_delimiter + file_index +\
               settings.log_file_delimiter + '.txt'

    open(filepath, 'w').close()
    log.info('created log file ' + filepath)
    return filepath


def __create_new_downloader_completed_log_file(file_index):
    filepath = settings.downloader_logging_file_completed_path + get_date() +\
               settings.log_file_delimiter + 'id' + settings.log_file_delimiter + file_index +\
               settings.log_file_delimiter + '.txt'

    open(filepath, 'w').close()
    log.info('created log file ' + filepath)
    return filepath


def __create_new_downloader_failed_log_file(file_index):
    filepath = settings.downloader_logging_file_failed_path + get_date() +\
               settings.log_file_delimiter + 'id' + settings.log_file_delimiter + file_index +\
               settings.log_file_delimiter + '.txt'

    open(filepath, 'w').close()
    log.info('created log file ' + filepath)
    return filepath


def print_stdout_output(pp):
    result = ''
    while True:
        line = pp.stdout.readline().rstrip('\n')
        if not line:
            break

        else:
            print line
            result += line

    return result


if __name__ == '__main__':
    print get_latest_downloader_completed_log_filepath()